package lee.vioson.ebook.ui.components

import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavHostController
import lee.vioson.ebook.data.AppContainer
import lee.vioson.ebook.viewmodels.SearchViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import androidx.navigation.compose.rememberNavController
import lee.vioson.composecommon.widgets.Input
import lee.vioson.composecommon.widgets.placeHolder
import lee.vioson.ebook.R
import lee.vioson.ebook.ui.AppTheme

/**
 *Author:viosonlee
 *Date:2023/6/15
 *DESCRIPTION:
 */
@Composable
fun SearchScreen(
    navHostController: NavHostController,
    appContainer: AppContainer,
    viewModel: SearchViewModel = viewModel(factory = viewModelFactory {
        initializer {
            SearchViewModel(appContainer)
        }
    })
) {
    val state by viewModel.state.collectAsState()
    MviScreen(viewModel = viewModel) {
        Column(
            Modifier
                .fillMaxSize()
                .statusBarsPadding()
        ) {
            SearchBar(viewModel)
            if (state.showResultLabel) {
                ResultLabel(state.keyword, state.results.size)
                Spacer(modifier = Modifier.height(10.dp))
            }
            LazyVerticalGrid(
                columns = GridCells.Fixed(3),
                modifier = Modifier.padding(horizontal = 13.dp),
                verticalArrangement = Arrangement.spacedBy(10.dp),
                horizontalArrangement = Arrangement.spacedBy(10.dp),
                content = {
                    items(state.results) {
                        BookCard(book = it, navHostController = navHostController)
                    }
                })
        }
    }
}

@Composable
fun SearchBar(viewModel: SearchViewModel) {
    val state by viewModel.state.collectAsState()
    Row(
        modifier = Modifier
            .padding(horizontal = 13.dp, vertical = 10.dp)
            .fillMaxWidth()
            .height(48.dp)
            .border(
                width = 1.dp,
                color = AppTheme.appColors.searchBarBorder,
                shape = RoundedCornerShape(4.dp)
            )
            .padding(horizontal = 16.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Input(
            modifier = Modifier.weight(1f),
            inputTxt = state.keyword,
            onValueChange = { viewModel.sendEvent(SearchViewModel.Event.OnKeywordChange(it)) },
            textStyle = TextStyle(fontSize = 14.sp, color = AppTheme.colors.onBackground),
            placeholder = placeHolder(
                id = R.string.Search_comics,
                textStyle = TextStyle(
                    fontSize = 14.sp,
                    color = AppTheme.appColors.grayTextColor
                )
            ),
            keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
            keyboardActions = KeyboardActions(onSearch = {
                //page 1 on new keyword
                viewModel.sendEvent(SearchViewModel.Event.OnPageChange(1))
                viewModel.doSearch(
                    state.page,
                    state.keyword
                )
            })
        )
        Text(
            text = stringResource(id = R.string.Search),
            fontSize = 18.sp,
            color = AppTheme.colors.onBackground,
            modifier = Modifier.clickable {
                //page 1 on new keyword
                viewModel.sendEvent(SearchViewModel.Event.OnPageChange(1))
                viewModel.doSearch(state.page, state.keyword)
            }
        )
    }
}

@Composable
fun ResultLabel(keyword: String, resultCount: Int) {
    Text(
        buildAnnotatedString {
            withStyle(style = SpanStyle(color = AppTheme.colors.onBackground)) {
                append(stringResource(id = R.string.search_result_label, resultCount))
            }
            withStyle(style = SpanStyle(color = AppTheme.colors.primary)) {
                append(keyword)
            }
            withStyle(style = SpanStyle(color = AppTheme.colors.onBackground)) {
                append("\'")
            }
        },
        modifier = Modifier.padding(horizontal = 16.dp),
    )

}

@Preview
@Composable
fun SearchScreenPreview() {
    ResultLabel(keyword = "keyword", resultCount = 4)
}